package com.sqtracker.recommender.service;

import com.sqtracker.recommender.model.Rating;
import com.sqtracker.recommender.repository.RatingRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.Optional;

@Service
public class RatingService {
    private static final Logger logger = LoggerFactory.getLogger(RatingService.class);

    private final RatingRepository ratingRepository;

    @Autowired
    public RatingService(RatingRepository ratingRepository) {
        this.ratingRepository = ratingRepository;
    }

    public Rating createOrUpdateRating(String userId, String torrentId, int score, String comment) {
        Optional<Rating> existingRating = ratingRepository.findByUserIdAndTorrentId(userId, torrentId);
        
        Rating rating;
        if (existingRating.isPresent()) {
            rating = existingRating.get();
            rating.setScore(score);
            rating.setComment(comment);
            rating.setUpdatedAt(Instant.now());
        } else {
            rating = new Rating();
            rating.setUserId(userId);
            rating.setTorrentId(torrentId);
            rating.setScore(score);
            rating.setComment(comment);
        }

        return ratingRepository.save(rating);
    }

    public List<Rating> getTorrentRatings(String torrentId) {
        return ratingRepository.findByTorrentId(torrentId);
    }

    public List<Rating> getUserRatings(String userId) {
        return ratingRepository.findByUserId(userId);
    }

    public Optional<Rating> getUserRatingForTorrent(String userId, String torrentId) {
        return ratingRepository.findByUserIdAndTorrentId(userId, torrentId);
    }

    public double getAverageRating(String torrentId) {
        return ratingRepository.getAverageScoreByTorrentId(torrentId);
    }

    public long getRatingCount(String torrentId) {
        return ratingRepository.countByTorrentId(torrentId);
    }

    public void deleteRating(String ratingId) {
        ratingRepository.deleteById(ratingId);
    }
} 